﻿using System;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace EpiNEXT.Presentation.Controls.Converters
{
    public class ByteArrayToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return null;
            if (String.IsNullOrEmpty(value.ToString().Trim())) return null;

            byte[] imageBytes = (byte[])value;
            System.Windows.Media.Imaging.BitmapImage bitmapimage = new System.Windows.Media.Imaging.BitmapImage();

            bitmapimage.BeginInit();
            MemoryStream imageStream = new MemoryStream(imageBytes);
            bitmapimage.StreamSource = imageStream;
            bitmapimage.EndInit();

            bitmapimage.Freeze();

            return bitmapimage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BitmapImage bitmapImage = value as BitmapImage;
            byte[] imageData;
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                encoder.Save(ms);
                imageData = ms.ToArray();
            }

            return imageData;
        }
    }
}
